<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules, ElForm } from 'element-plus'
import type { IAccount } from '@/types'
import { ElMessage } from 'element-plus'
import useLoginStore from '@/stores/login'
import { localCache } from '@/utils/cache'

// 定义内部的数据
const account = reactive<IAccount>({
  name: localCache.getCache('name') ?? '',
  password: localCache.getCache('password') ?? ''
})

const loginStore = useLoginStore()
const formRef = ref<InstanceType<typeof ElForm>>()
// 定义内部的方法
function loginAccount(isRememberPwd: boolean) {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      loginStore.loginAccountAction({ name, password }).then((res) => {
        console.log(res)
        if (isRememberPwd) {
          localCache.setCache('name', name)
          localCache.setCache('password', password)
        } else {
          localCache.removeCache('name')
          localCache.removeCache('password')
        }
      })
    } else {
      ElMessage.error('登录失败')
    }
  })
}

// 定义form的验证规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '必须输入用户名~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,20}$/, message: '必须是3~20个字母或数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须输入密码~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{6,}$/, message: '密码必须在6位以上', trigger: 'blur' }
  ]
}

// 定义暴露的属性和方法
defineExpose({
  loginAccount
})
</script>

<template>
  <div class="account">
    <el-form :model="account" label-width="60px" ref="formRef" :rules="accountRules" size="large">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="less" scoped>
</style>
